package com.pmt.feedplayer.platform

import android.media.MediaPlayer
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import com.pmt.feedplayer.data.PlaybackState
import com.pmt.feedplayer.data.PlaybackProgress
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.filterNotNull
import java.io.IOException

/**
 * Android平台的Player接口实现
 */
actual interface Player {
    /**
     * 播放状态流
     */
    actual val playbackStateFlow: Flow<PlaybackState>
    
    /**
     * 播放进度流
     */
    actual val progressFlow: Flow<PlaybackProgress>
    
    /**
     * 错误信息流
     */
    actual val errorFlow: Flow<String>
    
    /**
     * 设置播放源
     */
    actual fun setDataSource(url: String)
    
    /**
     * 开始播放
     */
    actual fun play()
    
    /**
     * 暂停播放
     */
    actual fun pause()
    
    /**
     * 跳转到指定位置
     */
    actual fun seekTo(position: Long)
    
    /**
     * 设置音量
     */
    actual fun setVolume(volume: Float)
    
    /**
     * 释放播放器资源
     */
    actual fun release()
    
    /**
     * 获取播放器视图的平台特定实现
     */
    actual fun getPlayerView(): Any?
}

/**
 * Android平台的Player实现类
 */
class PlayerImpl : Player, MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, 
    MediaPlayer.OnErrorListener, MediaPlayer.OnInfoListener {
    // 使用MutableStateFlow作为状态流的实现
    private val _playbackStateFlow = MutableStateFlow<PlaybackState>(PlaybackState.IDLE)
    private val _progressFlow = MutableStateFlow<PlaybackProgress>(PlaybackProgress(0L, 0L, 0L))
    private val _errorFlow = MutableStateFlow<String?>(null)
    
    // Android MediaPlayer实例
    private var mediaPlayer: MediaPlayer? = null
    private var currentUrl: String? = null
    private var isLooping = false
    
    // 进度更新的Handler
    private val handler = Handler(Looper.getMainLooper())
    private val progressUpdateRunnable = object : Runnable {
        override fun run() {
            updateProgress()
            handler.postDelayed(this, 1000) // 每秒更新一次进度
        }
    }
    
    // 实现接口的flow属性
    override val playbackStateFlow: Flow<PlaybackState> = _playbackStateFlow
    override val progressFlow: Flow<PlaybackProgress> = _progressFlow
    override val errorFlow: Flow<String> = _errorFlow.asSharedFlow().filterNotNull()
    
    init {
        createMediaPlayer()
    }
    
    private fun createMediaPlayer() {
        try {
            mediaPlayer = MediaPlayer().apply {
                setOnPreparedListener(this@PlayerImpl)
                setOnCompletionListener(this@PlayerImpl)
                setOnErrorListener(this@PlayerImpl)
                setOnInfoListener(this@PlayerImpl)
            }
            _playbackStateFlow.value = PlaybackState.IDLE
        } catch (e: Exception) {
            _errorFlow.value = "创建MediaPlayer失败: ${e.message}"
        }
    }
    
    override fun setDataSource(url: String) {
        try {
            currentUrl = url
            
            // 重置播放器状态
            mediaPlayer?.reset()
            
            // 设置数据源
            if (url.startsWith("http://") || url.startsWith("https://")) {
                mediaPlayer?.setDataSource(url)
            } else {
                // 本地文件路径
                mediaPlayer?.setDataSource(url)
            }
            
            // 准备播放
            mediaPlayer?.prepareAsync()
            _playbackStateFlow.value = PlaybackState.PREPARING
        } catch (e: IOException) {
            _errorFlow.value = "设置数据源失败: ${e.message}"
            _playbackStateFlow.value = PlaybackState.ERROR
        } catch (e: Exception) {
            _errorFlow.value = "设置数据源时发生错误: ${e.message}"
            _playbackStateFlow.value = PlaybackState.ERROR
        }
    }
    
    override fun play() {
        try {
            if (mediaPlayer?.isPlaying == false) {
                mediaPlayer?.start()
                _playbackStateFlow.value = PlaybackState.PLAYING
                startProgressUpdates()
            }
        } catch (e: Exception) {
            _errorFlow.value = "播放失败: ${e.message}"
            _playbackStateFlow.value = PlaybackState.ERROR
        }
    }
    
    override fun pause() {
        try {
            if (mediaPlayer?.isPlaying == true) {
                mediaPlayer?.pause()
                _playbackStateFlow.value = PlaybackState.PAUSED
                stopProgressUpdates()
            }
        } catch (e: Exception) {
            _errorFlow.value = "暂停失败: ${e.message}"
        }
    }
    
    override fun seekTo(position: Long) {
        try {
            mediaPlayer?.seekTo(position.toInt())
            updateProgress()
        } catch (e: Exception) {
            _errorFlow.value = "跳转失败: ${e.message}"
        }
    }
    
    override fun setVolume(volume: Float) {
        try {
            mediaPlayer?.setVolume(volume, volume) // 左右声道设置相同音量
        } catch (e: Exception) {
            _errorFlow.value = "设置音量失败: ${e.message}"
        }
    }
    
    override fun release() {
        stopProgressUpdates()
        try {
            mediaPlayer?.release()
            mediaPlayer = null
            currentUrl = null
            _playbackStateFlow.value = PlaybackState.IDLE
            _progressFlow.value = PlaybackProgress(0L, 0L, 0L)
        } catch (e: Exception) {
            _errorFlow.value = "释放资源失败: ${e.message}"
        }
    }

    override fun getPlayerView(): Any? {
        // 音频播放不需要视图
        return null
    }
    
    // MediaPlayer监听器实现
    override fun onPrepared(mp: MediaPlayer?) {
        // 准备完成后不需要显式设置状态，play()方法会设置为PLAYING
        // _playbackStateFlow.value = PlaybackState.PLAYING
        updateProgress()
    }
    
    override fun onCompletion(mp: MediaPlayer?) {
        _playbackStateFlow.value = PlaybackState.ENDED
        stopProgressUpdates()
        updateProgress()
        
        // 如果设置了循环播放，则重新开始
        if (isLooping) {
            mp?.seekTo(0)
            mp?.start()
            _playbackStateFlow.value = PlaybackState.PLAYING
            startProgressUpdates()
        }
    }
    
    override fun onError(mp: MediaPlayer?, what: Int, extra: Int): Boolean {
        val errorMessage = when (what) {
            MediaPlayer.MEDIA_ERROR_UNKNOWN -> "未知错误"
            MediaPlayer.MEDIA_ERROR_SERVER_DIED -> "媒体服务器死亡"
            else -> "错误代码: $what, 额外信息: $extra"
        }
        _errorFlow.value = "播放错误: $errorMessage"
        _playbackStateFlow.value = PlaybackState.ERROR
        stopProgressUpdates()
        return true // 已处理错误
    }
    
    override fun onInfo(mp: MediaPlayer?, what: Int, extra: Int): Boolean {
        when (what) {
            MediaPlayer.MEDIA_INFO_BUFFERING_START -> {
                if (mp?.isPlaying == true) {
                    _playbackStateFlow.value = PlaybackState.BUFFERING
                }
            }
            MediaPlayer.MEDIA_INFO_BUFFERING_END -> {
                if (mp?.isPlaying == true) {
                    _playbackStateFlow.value = PlaybackState.PLAYING
                }
            }
        }
        return false // 让系统处理其他信息
    }
    
    // 进度更新相关方法
    private fun startProgressUpdates() {
        handler.removeCallbacks(progressUpdateRunnable)
        handler.postDelayed(progressUpdateRunnable, 1000)
    }
    
    private fun stopProgressUpdates() {
        handler.removeCallbacks(progressUpdateRunnable)
    }
    
    private fun updateProgress() {
        mediaPlayer?.let { mp ->
            val currentPos = mp.currentPosition.toLong()
            val duration = mp.duration.toLong()
            // MediaPlayer没有直接的bufferedPosition属性，使用currentPos作为近似值
            val bufferedPos = currentPos
            
            _progressFlow.value = PlaybackProgress(currentPos, duration, bufferedPos)
        }
    }
}

/**
 * 创建平台特定的播放器实例
 */
actual fun createPlayer(): Player = PlayerImpl()